package com.zhf.demo02;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

/**
 * @Author: ZhaoHuanfeng
 * @Date: 2020/10/12 23:55
 */
public class ContextServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //配置参数的获取
        ServletConfig servletConfig = getServletConfig();
        ServletContext servletContext = servletConfig.getServletContext();
        Enumeration<String> initParameterNames = servletContext.getInitParameterNames();
        while (initParameterNames.hasMoreElements()){
            String s = initParameterNames.nextElement();
            System.out.println("参数名："+s+" 对应的值为："+servletContext.getInitParameter(s));
        }
        System.out.println("----------------------------");
        //相关路径的获取
        //本质上就是获取工程路径
        String contextPath = servletContext.getContextPath();
        System.out.println("获取上下文关联的路径信息为："+contextPath); //   /task01_demo02

        //获取实际路径信息
        //最终获取到的是部署的工程路径信息
        String realPath = servletContext.getRealPath("/");
        System.out.println("获取到的实际路径信息为："+realPath);
        System.out.println("----------------------------");

        //设置和获取属性信息
        servletContext.setAttribute("key","value");
        Object key = servletContext.getAttribute("key");
        System.out.println("根据参数指定的属性名获取到的属性值为："+key);
        servletContext.removeAttribute("key");
        key=servletContext.getAttribute("key");
        System.out.println("根据参数指定的属性名获取到的属性值为："+key);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
